<?php
// +----------------------------------------------------------------------
// | HkCms 内容模型
// +----------------------------------------------------------------------
// | Copyright (c) 2012-2019 http://www.hkcms.cn, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 广州恒企教育科技有限公司 <admin@hkcms.cn>
// +----------------------------------------------------------------------

namespace app\content\model;

use common\model\Model as CommModel;
use think\Db;

class Content extends CommModel {

    public $modelid = 0;

    public $_table;

    /**
     * 取得内容模型实例
     * @param $modelid
     * @return bool
     */
    static public function getInstance($modelid) 
    {
        //静态成品变量 保存全局实例
        static $_instance = NULL;

        //内容模型缓存
        $modelCache = hk_cache("Model");
        if (empty($modelCache[$modelid])) {
            return false;
        }
        $tableName = $modelCache[$modelid]['tablename'];

        if ( !isset($_instance[$modelid]) || is_null($_instance[$modelid]) ) {

            $_instance[$modelid] = new Content();
            $_instance[$modelid] = $_instance[$modelid]->set_table($tableName);

            //设置模型id
            $_instance[$modelid]->modelid = $modelid;
        } else {
            $_instance[$modelid]->set_table($tableName);
        }
        return $_instance[$modelid];
    }

    public function set_table($tablename='')
    {   
        $Db_config = config('database');
        $table = $Db_config['prefix'].$tablename;
        $this->_table = $table;

        $this->table = $table;

        $this->setTable($table);
        return $this;
    }

    public function relation($flag = true){
        
        if ($flag) {
            return $this->alias('a')->join($this->_table.'_data',$this->_table.'_data'.'.'.'id='.$this->_table.'.'.'id','LEFT');
        }

        return $this;        
    }

    /**
     * 获取关联定义名称
     * @param type $tableName 表名
     * @return type
     */
    public function getRelationName($tableName = '') {
        if (empty($tableName)) {
            $tableName = $this->name;
        }
        return ucwords($tableName) . 'Data';
    }

    /**
     * 获取_data模型
     */
    public function relation_model()
    {
        $tableName = strtolower($this->_table).'_data';

        return $this->table($tableName);
    }

     /**
     * 对通过连表查询的数据进行合并处理
     * @param $data
     * @return array
     */
     public function dataMerger(&$data) {
         $relationName = strtolower($this->_table).'_data';
         $datafb = db()->table($relationName)->where(['id'=>$data['id']])->find();
         if (!empty($datafb) && is_array($datafb)) {
             if (!empty($datafb['download'])) {
                 $datafb['download']= unserialize($datafb['download']);
             }
             if (!empty($datafb['imgs'])) {
                 $datafb['imgs']= unserialize($datafb['imgs']);
             }
             $data = array_merge($data, $datafb);
         }
         return $data;
     }

    /**
     * 是否终极栏目
     * @param type $catid
     * @return boolean
     */
    public function isUltimate($catid) {
        if (getCategory($catid, 'child')) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 信息锁定
     * @param type $catid 栏目ID
     * @param type $id 信息ID
     * @param type $userid 用户名ID
     * @param type $username 用户名
     * @return type
     */
    public function locking($catid, $id, $userid = 0) {
        $db = Db::name("Locking");
        $time = time();
        //锁定有效时间
        $Lock_the_effective_time = 300;
        if (empty($userid)) {
            $userid = \app\Admin\Service\User::getInstance()->id;
        }
        $where = array();
        $where['catid'] = array("EQ", $catid);
        $where['id'] = array("EQ", $id);
        $where['locktime'] = array("EGT", $time - $Lock_the_effective_time);
        $info = $db->where($where)->find();
        if ($info && $info['userid'] != \app\Admin\Service\User::getInstance()->id) {
            $this->error = 'o(︶︿︶)o 唉，该信息已经被用户【<font color=\"red\">' . $info['username'] . '</font>】锁定~请稍后在修改！';
            return false;
        }
        //删除失效的
        $where = array();
        $where['locktime'] = array("LT", $time - $Lock_the_effective_time);
        $db->where($where)->delete();
        return true;
    }

    /**
     * 内容模型处理类生成
     */
    public static function classGenerate() {
        //字段类型存放目录
        $fields_path = APP_PATH . 'content/fields/';
        //内置字段类型列表
        $fields = include $fields_path . 'fields.inc.php';
        $fields = $fields? : array();
        //更新内容模型数据处理相关类
        $classtypes = array('form', 'input', 'output', 'update', 'delete');
        //缓存生成路径
        $cachemodepath = RUNTIME_PATH;
        foreach ($classtypes as $classtype) {
            $content_cache_data = file_get_contents($fields_path . "content_$classtype.php");
            $cache_data = '';
            //循环字段列表，把各个字段的 form.inc.php 文件合并到 缓存 content_form.php 文件
            foreach ($fields as $field => $fieldvalue) {
                //检查文件是否存在
                if (file_exists($fields_path . $field . DIRECTORY_SEPARATOR . $classtype . '.inc.php')) {
                    //读取文件，$classtype.inc.php 
                    $ca = file_get_contents($fields_path . $field . DIRECTORY_SEPARATOR . $classtype . '.inc.php');
                    $cache_data .= str_replace(array("<?php", "?>"), "", $ca);
                }
            }
            $content_cache_data = str_replace('##{字段处理函数}##', $cache_data, $content_cache_data);
            //写入缓存
            file_put_contents($cachemodepath . 'content_' . $classtype . '.php', $content_cache_data);
            //设置权限
            chmod($cachemodepath . 'content_' . $classtype . '.php', 0777);
            unset($cache_data);
        }
    }

}
